package com.bittech.everything.core.common;

import com.bittech.everything.core.model.FileType;
import com.bittech.everything.core.model.Thing;

import java.io.File;

/**
 * Author: secondriver
 * Created: 2018/10/10
 */
public class FileConvertThing {
    
    /**
     * 文件对象转实体对象
     *
     * @param file
     * @return
     */
    public static Thing convert(File file) {
        Thing thing = new Thing();
        thing.setName(file.getName());
        thing.setDepth(computeDepth(file.getPath()));
        thing.setFileType(computeFileType(file.getPath()));
        thing.setPath(file.getAbsolutePath());
        return thing;
    }
    
    /**
     * 计算路径深度
     *
     * @param path
     * @return
     */
    private static int computeDepth(String path) {
        int depth = -1;
        for (char ch : path.toCharArray()) {
            if (ch == File.separatorChar) {
                depth++;
            }
        }
        return depth;
    }
    
    /**
     * 计算文件类型
     *
     * @param path
     * @return
     */
    private static FileType computeFileType(String path) {
        File file = new File(path);
        if (file.isDirectory()) {
            return FileType.OTHER;
        } else {
            int index = path.lastIndexOf(".");
            if (index == -1) {
                return FileType.OTHER;
            } else {
                return FileType.lookup(path.substring(index + 1));
            }
        }
    }
}
